package com.xiaoyu.izf.controller.api;

import com.xiaoyu.izf.model.UserInfo;
import com.xiaoyu.izf.model.exception.BusinessException;
import com.xiaoyu.izf.model.exception.BusinessStatusEnum;
import com.xiaoyu.izf.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

@Controller
public class BaseApiController {

    @Autowired
    private UserInfoService userInfoService;

    public UserInfo getUserByToken(HttpServletRequest request){
        String token = request.getHeader("token");
        if(!StringUtils.isEmpty(token)){
            UserInfo user = userInfoService.userInfoByToken(token);
            if (user!=null)
                return user;
        }
        throw new BusinessException(BusinessStatusEnum.NOT_LOGIN);
    }

    public String getip(HttpServletRequest request) {
        String ip = request.getHeader("X-Real-IP");
        // System.out.println("X-Real-IP:"+ip);
        if (ip == null || ip.isEmpty()) {
            ip = request.getHeader("X-Forwarded-For");
            // System.out.println("X-Forwarded-For:"+ip);
        }
        if (ip == null || ip.isEmpty()) {
            ip = request.getRemoteAddr();
        }

        if (ip == null || ip.isEmpty()) {
            ip = "";
        }
        return ip;
    }
}
